<script lang="ts" setup>
import { updateUserPwd } from '@/api/system/user/user'
import { toastSuccess } from '@/utils/common'

definePage({
  style: {
    navigationBarTitleText: '修改密码',
  },
})

const form = ref()

const user = reactive({
  oldPassword: undefined,
  newPassword: undefined,
  confirmPassword: undefined,
})

function validatorPassword(val) {
  return user.newPassword === val
}

function handleSubmit() {
  form.value
    .validate()
    .then(({ valid, errors }) => {
      if (valid) {
        updateUserPwd(user.oldPassword, user.newPassword).then((response) => {
          toastSuccess('修改成功')
          uni.navigateBack()
        })
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}
</script>

<template>
  <view class="page">
    <wd-form ref="form" :model="user" error-type="toast">
      <wd-cell-group border>
        <wd-input
          v-model="user.oldPassword"
          label="旧密码"
          label-width="100px"
          prop="oldPassword"
          clearable
          show-password
          placeholder="请输入旧密码"
          :rules="[{ required: true, message: '旧密码不能为空' }]"
        />
        <wd-input
          v-model="user.newPassword"
          label="新密码"
          label-width="100px"
          prop="newPassword"
          clearable
          show-password
          placeholder="请输入新密码"
          :rules="[{ required: true, pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/, message: '需包含字母和数字，6-20位字符' }]"
        />
        <wd-input
          v-model="user.confirmPassword"
          label="确认密码"
          label-width="100px"
          prop="confirmPassword"
          clearable
          show-password
          placeholder="请输入确认密码"
          :rules="[{ required: true, validator: validatorPassword, message: '两次输入的密码不一致' }]"
        />
      </wd-cell-group>
      <view class="page-content">
        <wd-button type="primary" block @click="handleSubmit">
          提 交
        </wd-button>
      </view>
    </wd-form>
  </view>
</template>

<style lang="scss" scoped>
//
</style>
